﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Read.Application.Command.PackagingQualityCommand;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Read.Application.CommandHander.PackagingQualityHandler
{
    public class GetPackagingQualityHandler : IRequestHandler<GetPackagingQualityCommand, APIResult<APIPaging<PackagingQuality>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetPackagingQualityHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<APIResult<APIPaging<PackagingQuality>>> Handle(GetPackagingQualityCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<PackagingQuality>> result = new APIResult<APIPaging<PackagingQuality>>();

            // 初始化参数集合
            var parameters = new SugarParameter[] { };
            var conditions = new List<string>();
            conditions.Add("IsDel = 0");

            // 动态添加查询条件
            if (!string.IsNullOrEmpty(request.batchNumber))
            {
                conditions.Add("batchNumber LIKE @batchNumber");
                parameters = parameters.Concat(new[] { new SugarParameter("@batchNumber", $"%{request.batchNumber}%") }).ToArray();
            }

            if (request.productionDate != null)
            {
                conditions.Add("DATE(productionDate) = @productionDate");
                parameters = parameters.Concat(new[] { new SugarParameter("@productionDate", request.productionDate.Value.Date) }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.packagingType))
            {
                conditions.Add("packagingType LIKE @packagingType");
                parameters = parameters.Concat(new[] { new SugarParameter("@packagingType", $"%{request.packagingType}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.labelQuality))
            {
                conditions.Add("labelQuality LIKE @labelQuality");
                parameters = parameters.Concat(new[] { new SugarParameter("@labelQuality", $"%{request.labelQuality}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.capSealing))
            {
                conditions.Add("capSealing LIKE @capSealing");
                parameters = parameters.Concat(new[] { new SugarParameter("@capSealing", $"%{request.capSealing}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.bottleCondition))
            {
                conditions.Add("bottleCondition LIKE @bottleCondition");
                parameters = parameters.Concat(new[] { new SugarParameter("@bottleCondition", $"%{request.bottleCondition}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.fillLevel))
            {
                conditions.Add("fillLevel LIKE @fillLevel");
                parameters = parameters.Concat(new[] { new SugarParameter("@fillLevel", $"%{request.fillLevel}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.Flexibility))
            {
                conditions.Add("Flexibility = @Flexibility");
                parameters = parameters.Concat(new[] { new SugarParameter("@Flexibility", $"%{request.Flexibility}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.WaterResistance))
            {
                conditions.Add("WaterResistance = @WaterResistance");
                parameters = parameters.Concat(new[] { new SugarParameter("@WaterResistance", $"%{request.WaterResistance}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.Breathability))
            {
                conditions.Add("Breathability = @Breathability");
                parameters = parameters.Concat(new[] { new SugarParameter("@Breathability", $"%{request.Breathability}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.SurfaceFlatness))
            {
                conditions.Add("SurfaceFlatness = @SurfaceFlatness");
                parameters = parameters.Concat(new[] { new SugarParameter("@SurfaceFlatness", $"%{request.SurfaceFlatness}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.ColorConsistency))
            {
                conditions.Add("ColorConsistency = @ColorConsistency");
                parameters = parameters.Concat(new[] { new SugarParameter("@ColorConsistency", $"%{request.ColorConsistency}%") }).ToArray();
            }

            if (!string.IsNullOrEmpty(request.inspectorName))
            {
                conditions.Add("inspectorName LIKE @inspectorName");
                parameters = parameters.Concat(new[] { new SugarParameter("@inspectorName", $"%{request.inspectorName}%") }).ToArray();
            }

            if (request.inspectionResult.HasValue)
            {
                conditions.Add("inspectionResult = @inspectionResult");
                parameters = parameters.Concat(new[] { new SugarParameter("@inspectionResult", request.inspectionResult.Value) }).ToArray();
            }

            if (request.inspectionDate != null)
            {
                conditions.Add("DATE(inspectionDate) = @inspectionDate");
                parameters = parameters.Concat(new[] { new SugarParameter("@inspectionDate", request.inspectionDate.Value.Date) }).ToArray();
            }

            // 构建查询条件字符串
            string whereClause = string.Join(" AND ", conditions);

            // 统计符合条件的记录总数
            string countQuery;
            if (string.IsNullOrEmpty(whereClause))
            {
                countQuery = "SELECT COUNT(*) FROM PackagingQuality";
            }
            else
            {
                countQuery = $"SELECT COUNT(*) FROM PackagingQuality WHERE {whereClause}";
            }
            // 去掉泛型使用，进行类型转换
            object scalarResult = await db.Ado.GetScalarAsync(countQuery, parameters);
            int totalCount = Convert.ToInt32(scalarResult);

            // 计算总页数
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);

            // 构建分页查询语句
            string selectQuery;
            if (string.IsNullOrEmpty(whereClause))
            {
                selectQuery = $"SELECT * FROM PackagingQuality ORDER BY batchNumber DESC LIMIT @offset, @pageSize";
            }
            else
            {
                selectQuery = $"SELECT * FROM PackagingQuality WHERE {whereClause} ORDER BY batchNumber DESC LIMIT @offset, @pageSize";
            }
            parameters = parameters.Concat(new[] {
        new SugarParameter("@offset", (request.pageindex - 1) * request.pageSize),
        new SugarParameter("@pageSize", request.pageSize)
    }).ToArray();

            // 执行分页查询
            var list = await db.Ado.SqlQueryAsync<PackagingQuality>(selectQuery, parameters);

            // 封装分页结果
            APIPaging<PackagingQuality> paging = new APIPaging<PackagingQuality>()
            {
                TotalCount = totalCount,
                TotalPage = pageCount,
                list = list.ToList()
            };

            result.code = APIResultCode.success;
            result.msg = "包装成品质检显示成功";
            result.data = paging;
            return result;
        }
    }
}
